<template>
  <div class="machine-detail">
    <h2>机器详细分析</h2>
    <el-form :model="filters" label-width="100px" class="filter-form">
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="机器类别">
        <el-select v-model="filters.machineCategory" placeholder="请选择" clearable>
          <el-option label="所有" value="" />
          <el-option
            v-for="group in agriculturalMachines"
            :key="group.title"
            :label="group.title"
            :value="group.title"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机器名称">
        <el-input v-model="filters.machineName" placeholder="输入机器名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="applyFilters" :loading="loading">查询</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="machineStore.machines"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="机器名称" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ row.status === 'NORMAL' ? '正常' : row.status === 'FAULT' ? '故障' : '维护中' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="usageCount" label="使用次数" />
    </el-table>
    <el-pagination
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px;"
    />
    <el-button
      type="primary"
      @click="compareMachines"
      :disabled="selectedMachines.length !== 2"
      style="margin-top: 20px;"
    >
      对比选中机器
    </el-button>
    <div class="charts">
      <div id="usage-chart" style="width: 100%; height: 400px;"></div>
      <div id="failure-chart" style="width: 100%; height: 400px;"></div>
    </div>

    <!-- 对比弹窗 -->
    <el-dialog
      v-model="compareDialogVisible"
      title="机器对比"
      width="60%"
      :before-close="closeCompareDialog"
    >
      <el-table :data="selectedMachines" style="width: 100%">
        <el-table-column prop="name" label="机器名称" />
        <el-table-column prop="type" label="类型" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ row.status === 'NORMAL' ? '正常' : row.status === 'FAULT' ? '故障' : '维护中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageCount" label="使用次数" />
        <el-table-column prop="registerTime" label="注册时间" />
      </el-table>
      <div id="compare-chart" style="width: 100%; height: 400px; margin-top: 20px;"></div>
      <template #footer>
        <el-button @click="closeCompareDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import { useMachineStore } from '@/stores/machine';
import { useAgriculturalDataStore } from '@/stores/agriculturalData';

const machineStore = useMachineStore();
const agriculturalDataStore = useAgriculturalDataStore();
const filters = ref({
  startDate: '',
  endDate: '',
  machineCategory: '',
  machineName: '',
  machineNumber: '',
  ownerId: '',
  page: 1,
  size: 10,
});
const dateRange = ref<[string, string] | null>(null);
const selectedMachines = ref<any[]>([]);
const agriculturalMachines = agriculturalDataStore.getAgriculturalMachines;
const loading = ref(false);
const compareDialogVisible = ref(false);
const pagination = ref({
  page: 1,
  size: 10,
  total: 0,
});

const applyFilters = async () => {
  loading.value = true;
  try {
    if (dateRange.value) {
      filters.value.startDate = dateRange.value[0];
      filters.value.endDate = dateRange.value[1];
    } else {
      filters.value.startDate = '';
      filters.value.endDate = '';
    }
    filters.value.page = pagination.value.page;
    filters.value.size = pagination.value.size;
    machineStore.setFilters(filters.value);
    const [statsResponse, machinesResponse] = await Promise.all([
      machineStore.fetchStatistics(),
      machineStore.fetchMachines(),
    ]);
    pagination.value.total = machinesResponse?.data?.data?.totalElements || machineStore.machines.length;
    renderCharts();
    if (!machineStore.machines.length) {
      ElMessage.info('没有符合条件的机器数据');
    }
  } catch (error) {
    ElMessage.error('查询失败，请稍后重试');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const resetFilters = async () => {
  dateRange.value = null;
  filters.value = {
    startDate: '',
    endDate: '',
    machineCategory: '',
    machineName: '',
    machineNumber: '',
    ownerId: '',
    page: 1,
    size: 10,
  };
  pagination.value.page = 1;
  pagination.value.size = 10;
  machineStore.clearFilters();
  await applyFilters();
};

const handleSelectionChange = (val: any[]) => {
  selectedMachines.value = val;
};

const handleSizeChange = (size: number) => {
  pagination.value.size = size;
  pagination.value.page = 1;
  applyFilters();
};

const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
  applyFilters();
};

const compareMachines = () => {
  compareDialogVisible.value = true;
  setTimeout(() => renderCompareChart(), 0); // 确保 DOM 已渲染
};

const closeCompareDialog = () => {
  compareDialogVisible.value = false;
  selectedMachines.value = [];
};

const getStatusTagType = (status: string) => {
  return status === 'NORMAL' ? 'success' : status === 'FAULT' ? 'danger' : 'warning';
};

const renderCharts = () => {
  const usageChart = echarts.init(document.getElementById('usage-chart') as HTMLElement);
  usageChart.setOption({
    title: { text: '机器使用频率', left: 'center' },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: machineStore.statistics.usageFrequency.map((item) => item.date),
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '使用次数',
        type: 'line',
        data: machineStore.statistics.usageFrequency.map((item) => item.count),
      },
    ],
  });

  const failureChart = echarts.init(document.getElementById('failure-chart') as HTMLElement);
  failureChart.setOption({
    title: { text: '机器故障率', left: 'center' },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: machineStore.statistics.failureRate.map((item) => item.name),
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '故障次数',
        type: 'bar',
        data: machineStore.statistics.failureRate.map((item) => item.value),
      },
    ],
  });
};

const renderCompareChart = () => {
  const compareChart = echarts.init(document.getElementById('compare-chart') as HTMLElement);
  compareChart.setOption({
    title: { text: '机器使用次数对比', left: 'center' },
    tooltip: {},
    legend: { data: selectedMachines.value.map((m) => m.name), top: 30 },
    xAxis: { type: 'category', data: ['使用次数'] },
    yAxis: { type: 'value' },
    series: selectedMachines.value.map((machine) => ({
      name: machine.name,
      type: 'bar',
      data: [machine.usageCount],
    })),
  });
};

onMounted(applyFilters);
</script>

<style scoped>
.machine-detail {
  padding: 20px;
}
.filter-form {
  margin: 0 auto 50px;
  max-width: 800px;
}
.charts {
  margin-top: 40px;
}
</style>